﻿using System;
using System.Collections.Generic;

using Microsoft.StyleCop.CSharp;

namespace StyleCopContrib.CSharp.Rules
{
	internal class OrderingRules
	{
		internal static bool CheckUsingDirectivesMustBeginDocument(CsElement element,
			CsElement parentElement,
			DocumentAnalyzer context)
		{
			var violated = false;
			var usingDirective = (UsingDirective)element;
			if (usingDirective.ParentElement != null &&
				usingDirective.ParentElement.ElementType != ElementType.Root)
			{
				violated = true;
			}
			var siblings = new List<CsElement>(usingDirective.ParentElement.ChildElements);
			var indexOfThisUsing = siblings.IndexOf(usingDirective);
			for (var index = indexOfThisUsing - 1; index >= 0; index--)
			{
				var sibling = siblings[index];
				if (sibling.ElementType == ElementType.UsingDirective)
				{
					break;
				}
				violated = true;
				break;
			}
			if (violated)
			{
				context.AddViolation(
					usingDirective,
					usingDirective.LineNumber,
					RuleNames.UsingDirectivesMustBeginDocument);
			}
			return true;
		}
	}
}
